import logging
import re
import urllib.request
import ssl
import bs4
import dealmysql

# 解决urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED]
ssl._create_default_https_context = ssl._create_unverified_context

def get_beautifulsoup(url):
    '''根据url，请求网页，并返回获取到的BeautifulSoup对象
    '''
    response = urllib.request.urlopen(url)
    # ignore解决 can't decode byte 0x8b
    html = response.read().decode('utf-8', "ignore")
    soup = bs4.BeautifulSoup(html, 'lxml')
    return soup

def get_aqiyi_tv_set(query):
    '''获取爱奇艺的某个指定的搜索结果页面, 
    跳转到详情页，然后抓取剧集列表标签相关内容

    Args:
        query: 剧名字符串
    
    Return: 剧集列表标签右边的title-update-progress内容
    '''
    url = "http://so.iqiyi.com/so/q_"+urllib.parse.quote(query)
    soup = get_beautifulsoup(url)

    brief = soup.find('h3', {'class' : 'result_title'})
    if not brief:
        # 若是没有搜索结果，直接返回None
        logging.warning('爱奇艺中没搜到 %s 的结果' % query)
        return None

    url = brief.find('a').get('href')
    soup = get_beautifulsoup(url)
    brief = soup.select('.title-update-progress')
    return brief

def tv_is_finished(query):
    '''检测某部剧是否更新完成
    Args: 
        query: 剧名字符串
    
    Returns: yes表示更新完成，no表示未完成，unknown表示未知
    '''
    brief = get_aqiyi_tv_set(query)
    if not brief:
        logging.warning('未发现 %s 的剧情列表标签' % query)
        # 未发现剧情列表标签，返回字符串表示未知
        return 'unknown'

    set_string = brief[0].get_text().strip()
    if '更新' in set_string:
        # 此时 set_string 形如（更新至24集/共50集）
        if '/' in set_string:    # 超能力女儿 只显示了更新至某集
            update = set_string.split('/')
            left = re.sub(r'[^\d]','', update[0])
            right = re.sub(r'[^\d]','', update[1])
            if left == right:
                return 'yes'
            else:
                return 'no'
        else:
            return 'unknown'
    # 其余情况，算成更新完成
    return 'yes'

if __name__ == "__main__":
    mysql = dealmysql.DealMysql(
        host = "",
        user = "",
        password = "",
        database = "",
        charset='utf8',
        table = 'tv_now_playing'
    )
    mysql.connect()
    mysql.delete_all('tv_now_playing')

    tv_tuple = mysql.select(col_name = ['title', 'subject'], table = 'tv_douban_table')
    for item in tv_tuple:
        is_finished = tv_is_finished(item[0])
        print(item[0], 'is_finished: ', is_finished)
        mysql.insert([item[1], item[0], is_finished, 'tv'])